package cn.edu.nju.ws.sview.wyge.servlets;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import cn.edu.nju.ws.sview.wyge.relations.adataset.BasicTriplePattern;
import cn.edu.nju.ws.sview.wyge.relations.adataset.CustomDataset;
import cn.edu.nju.ws.sview.wyge.relations.adataset.entities.qxliu.algorithms.ClassTree;
import cn.edu.nju.ws.sview.wyge.relations.adataset.relations.TriplePattern;
import cn.edu.nju.ws.sview.wyge.relations.datasets.DatasetItem;

/**
 * 给定relation_id以及dataset得到relation的答案
 */
public class RelationExpandFromNew extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RelationExpandFromNew() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String params = null;
		response.setCharacterEncoding("utf-8");
		if (request.getParameter("data") != null) {
			params = request.getParameter("data");
			String str = URLDecoder.decode(params, "UTF-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			String ds_type = (String) regtJSON.get("ds_type");
			int ds_id = Integer.parseInt((String) regtJSON.get("ds_id"));

			ArrayList<Integer> docs = new ArrayList<Integer>();
			if (ds_type.equals("uri")) {
				docs.add(ds_id);
			} else if (ds_type.equals("custom")) {
				docs.addAll(CustomDataset.getURLIDsByCustomDatasetId(ds_id));
			}

			ArrayList<ArrayList<String>> expands = new BasicTriplePattern(docs)
					.getAll();

			JSONArray elements = new JSONArray();
			for (ArrayList<String> t : expands) {
				String s_code = t.get(0);
				String p_code = t.get(1);
				String o_code = t.get(2);
				// System.out.println(s_code + " " + p_code + " " + o_code);
				TriplePattern tp = TriplePattern.getTriple(s_code, p_code,
						o_code);
				JSONObject jsob = new JSONObject();
				jsob.put("stext", tp.getSubjectText());
				jsob.put("ptext", tp.getPropertyText());
				jsob.put("otext", tp.getObjectText());
				jsob.put("s", tp.getSubject());
				jsob.put("p", tp.getProperty());
				jsob.put("o", tp.getObject());
				elements.add(jsob);
			}

			JSONObject result = new JSONObject();
			result.put("result", elements);
			response.getWriter().print(result);
		}
		//for class selection dialog
		else if(request.getParameter("getclasses") != null){
			params = request.getParameter("getclasses");
			String str = URLDecoder.decode(params, "UTF-8");
			JSONObject regtJSON = (JSONObject)JSONValue.parse(str);
			String ds_type = (String)regtJSON.get("ds_type");
			int ds_id = Integer.valueOf((String)regtJSON.get("ds_id"));
			String idStr = (String)regtJSON.get("idStr");
			if(ds_id>0){
				Document doc = new ClassTree(ds_type, ds_id).makeDocument();
				response.getWriter().print(doc.asXML());
			}else{
				String[] strList = idStr.split("_");
				ArrayList<Integer> docs = new ArrayList<Integer>();
				for(String id :strList){
					if(id.trim().length()>0){
						docs.add(Integer.parseInt(id));
					}
				}
				Document doc = new ClassTree(docs).makeDocument();
				response.getWriter().print(doc.asXML());
			}
//			System.out.println(doc.asXML());
//			response.getWriter().print(doc.asXML());
		}
		//for class selection dialog
		else if(request.getParameter("getproperties") != null){
			params = request.getParameter("getproperties");
			String str = URLDecoder.decode(params, "UTF-8");
			JSONObject regtJSON = (JSONObject)JSONValue.parse(str);
			String ds_type = (String)regtJSON.get("ds_type");
			int ds_id = Integer.valueOf((String)regtJSON.get("ds_id"));
			String idStr = (String)regtJSON.get("idStr");
			

			ArrayList<Integer> docs = new ArrayList<Integer>();
			if (ds_type.equals(DatasetItem.URI_GENRE)) {
				docs.add(ds_id);
			} else if (ds_type.equals(DatasetItem.CUSTOM_GENRE)) {
				docs.addAll(CustomDataset.getURLIDsByCustomDatasetId(ds_id));
			}else if(ds_type.contentEquals(DatasetItem.TEMP_GENRE)){
				String[] strList = idStr.split("_");
				for(String id :strList){
					if(id.trim().length()>0){
						docs.add(Integer.parseInt(id));
					}
				}
			}

			ArrayList<ArrayList<String>> expands = new BasicTriplePattern(docs)
					.getProperties();

			JSONArray elements = new JSONArray();
			for (ArrayList<String> t : expands) {
				String s_code = t.get(0);
				String p_code = t.get(1);
				String o_code = t.get(2);
				TriplePattern tp = TriplePattern.getTriple(s_code, p_code, o_code);
				if(tp.getProperty()==478384){//=================rdf:type
					continue;
				}
				JSONObject jsob = new JSONObject();
				jsob.put("stext", tp.getSubjectText());
				jsob.put("ptext", tp.getPropertyText());
				jsob.put("otext", tp.getObjectText());
				jsob.put("s", tp.getSubject());
				jsob.put("p", tp.getProperty());
				jsob.put("o", tp.getObject());
				elements.add(jsob);
			}

			JSONObject result = new JSONObject();
			result.put("result", elements);
			System.out.println("in RelationExpandFromNew:"+result.toJSONString());
			response.getWriter().print(result);
		}		
	}//end of doPost
}
